<template>
    <div class="userSetting_block">
        <div class="top">
            <search-bar v-model="searchModel" :search-data="searchData" :config="searchData" @search="handleSearchSubmit"
                @searchReset="handleSearchReset" style="margin-top:0;margin-left:-20px;padding-top:.2rem">
            </search-bar>
        </div>

        <div class="bottom">

            <div class="btn_area" size="medium">
                <el-button type="primary" size="medium" @click="add">新增</el-button>
                <el-dropdown @command="handleCommand" style="margin-left: 0.1rem">
                    <el-button size="medium">
                        批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">

                        <el-dropdown-item command="delete">删除</el-dropdown-item>

                    </el-dropdown-menu>
                </el-dropdown>
                <el-button type="" size="medium" style="margin-left: 0.1rem" @click="exportWay">导出</el-button>
            </div>
            <LPTablePage :show-index="false" :table-data="tableData" :table-column="tableColumn" :total="total"
                :current-page="currentPage" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"
                :selection="true" @handleSelectionChange="handleSelectionChange" ref="tablePage" :selectable="selectable">
                <template slot="isEnabled" slot-scope="scope">
                    <!-- <span v-if="row.status == 0" class="green">
                        成功
                    </span>
                    <span v-else class="blue">
                        失败
                    </span>  -->
                    <el-switch v-model="scope.row.isEnabled" :active-value="2" :inactive-value="0"></el-switch>

                </template>



            </LPTablePage>
        </div>
        <!-- 编辑or新增 -->
        <base-dialog :visible="addVisile" :title="(isEdit ? '编辑' : '新增') + '用户'" width="918px" class="addDictDialog"
            @handleDialogSubmit="handleAddSubmit" @handleDialogCancle="handleAddCancle">
            <el-form ref="dictForm" :model="dictModel" :rules="ruleRule" label-width="120px" class="dictForm"
                label-position="top" size="medium">
                <el-row :gutter="50">

                    <el-col :span="24">
                        <el-form-item label="手机号:" prop="phone">
                            <el-input v-model.trim="dictModel.phone" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24" class="dirverForm">
                        <el-form-item label="绑定司机:" prop="driverId" :rules="getFormItemDriverRules()">

                            <el-select style="width:100%" v-model="dictModel.driverId"
                                :remote-method="getDriverQueryBindListWay" filterable default-first-option remote
                                placeholder="请选择" clearable>
                                <el-option v-for="(item) in driverListOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>

                        </el-form-item>
                    </el-col>
                    <el-col :span="24" class="dirverForm">
                        <el-form-item label="绑定物流公司:" prop="companyId" :rules="getFormItemCompanyRules()">

                            <el-select style="width:100%" v-model="dictModel.companyId"
                                :remote-method="getCompanyQueryCompanyListWay" filterable default-first-option remote
                                placeholder="请选择">
                                <el-option v-for="(item) in companyQueryCompanyList" :key="item.id"
                                    :label="item.companyName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="是否启用:" prop="isEnabled">

                            <el-switch v-model="dictModel.isEnabled" />
                            <span class="ml20">关闭后账号在系统停止使用</span>

                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </base-dialog>

    </div>
</template>
    
<script>
import { validateNumber } from "@/utils/validate";
import baseDialog from '@/components/BaseDialog'
import SearchBar from '@/components/SearchBar'
import LPTablePage from '@/components/LPTablePage'
import {
    logininforList,
    delLogininfor,
    cleanLogininfor
} from '@/api/system/logs'
import beiGangApi from '@/api/logistics/beigang'
import { addDateRange } from "@/utils/ruoyi";



// import {auditSuccess,auditReject} from "@/api/customer";


export default {
    name: "userSetting",
    components: {
        LPTablePage, SearchBar, baseDialog
    },
    data() {
        // 司机和物流公司判断是否绑定用户
        const validateBindStatusDriver = (rule, value, callback) => {
            let val = this.driverListOptions.filter(item => item.id == value)
            if (Number(val[0].bindStatus) == 1) {
                return callback(new Error("司机已被其他人绑定"));
            }
            else {
                callback();
            }
        }
        const validateBindStatusCom = (rule, value, callback) => {
            let val = this.companyQueryCompanyList.filter(item => item.id == value)

            if (Number(val[0].bindStatus) == 1) {
                return callback(new Error("物流公司已被其他人绑定"));
            }
            else {
                callback();
            }
        }
        const validateNumberF = (rule, value, callback) => {
            if (Number(value) == 1) {
                return callback(new Error("不能为0"));
            }
            if (!validateNumber(value)) {
                return callback(new Error("请输入正确数字"));
            } else {
                callback();
            }
        };
        const validateEmpty = (rule, value, callback) => {
            console.log('validateEmpty', value, value instanceof Array);
            if (!(value instanceof Array)) {
                return callback(new Error("必填"));
            }
            if (value instanceof Array && value.length == 0) {
                return callback(new Error("必填"));
            } else {
                callback()
            }
        };
        return {
            auditParams: {

            },
            addVisile: false,
            auditVisile: false,
            isEdit: false,
            dictModel: {

                isEnabled: true
            },
            searchModel: {},
            searchData: [


                { placeholder: "手机号", prop: "phone", },

                {
                    prop: 'isEnabled',
                    type: 'select',
                    placeholder: '是否启用',
                    options: [
                        { label: '未启用', value: 0 },
                        { label: '启用', value: 2 },

                    ]
                },
                {
                    prop: 'isBindDriver',
                    type: 'select',
                    placeholder: '是否绑定司机',
                    options: [
                        { label: '否', value: 0 },
                        { label: '是', value: 1 },

                    ]
                },
                {
                    prop: 'isBandCompany',
                    type: 'select',
                    placeholder: '是否绑定物流公司',
                    options: [
                        { label: '否', value: 0 },
                        { label: '是', value: 1 },
                    ]
                },

                {
                    prop: 'search',
                    type: 'button',
                    policy: ['system.log.query'],
                },
            ],
            tableData: [],

            tableColumn: [
                { label: "手机号", prop: "phone", },
                { label: "绑定司机", prop: "driverName" },
                { label: "绑定物流公司", prop: "companyName", },
                { label: "是否启用", prop: "isEnabled", render: true },
                { label: "操作时间", prop: "createTime", },
                { label: "操作人", prop: "createBy", },
                {
                    label: '操作',
                    prop: 'action',
                    fixed: 'right',
                    type: 'button',
                    width: 170,
                    buttons: [

                        {
                            label: '编辑',
                            type: 'text',
                            color: 'rgba(0, 118, 255, 1)',
                            method: 'handleEdit',

                        },

                        {
                            label: '删除',
                            type: 'text',
                            color: '#ee3333',
                            method: 'handleDelete',

                        },
                    ],
                },

                //  {
                //     label: "操作",
                //     prop: "action",
                //     type: "button",
                //     hideTooLtip:true,
                //     width:180,
                //     button:[
                //         {
                //             label: "查看",
                //             type: "text",
                //             icon: "el-icon-view",
                //             method:`_detail${this.$options.name}`
                //         },
                //         {
                //             label: "通过",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditSuccess${this.$options.name}`
                //         },
                //         {
                //             label: "驳回",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditFail${this.$options.name}`
                //         },
                //     ]
                //  }   
            ],
            total: 0,
            currentPage: 1,
            selectArr: [],
            allotVisile: false,
            allotModel: {},
            allotRule: {
                responsibleUserId: [
                    // { required: true, trigger: "blur", message: "必填" },
                    { validator: validateEmpty, required: true, trigger: "blur" }
                ],
            },
            userOptions: [],
            settingVisile: false,
            ruleModel: {},
            dictRule: {
                autoRecycleEnable: [{ required: true, trigger: "blur", message: "必填" }],
                autoRecycleByNotFollowUpOverDays: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" }],

                originalResponsibleUserTakeLimit: [{ required: true, trigger: "blur", message: "必填" }],
                originalResponsibleUserTakeLimitDays: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" },
                ],
                takeLimit: [{ required: true, trigger: "blur", message: "必填" }],
                takeLimitByEveryDayNumbers: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" },
                ],
                phone: [{ required: true, trigger: "blur", message: "必填" }],
                driverId: [{ required: true, trigger: "change", message: "必选" }],
                driverId: [{ required: true, trigger: "change", message: "必选" }],

            },
            ruleRule: {
                phone: [{ required: true, trigger: "blur", message: "必填" }],
                isEnabled: [{ required: true, trigger: "change", message: "必选" }],
                // driverId: [{ required: true, trigger: "change", message: "必选" },
                // { validator: validateBindStatusDriver, required: true, trigger: "change" }],
                // companyId: [{ required: true, trigger: "change", message: "必选" },
                // { validator: validateBindStatusCom, required: true, trigger: "change" }],
            },
            detailVisible: false,
            detailId: '',
            openSeaClueId: '',
            status: null,
            isCanTakeAudit: null,
            driverListOptions: [],
            companyQueryCompanyList: [],
        }
    },
    mounted() {
        this.getAccountList()
        // 详情
        this.$bus.$on('handleDetail', rows => {

            this.$router.push({ path: `/logistics/beiGang/userSettingDetail/${rows.infoId}` })
        })
        // 编辑
        this.$bus.$on('handleEdit', rows => {
            this.getDetail(rows.id)

        })
        // 审核
        this.$bus.$on('handleAudit', rows => {
            this.auditVisile = true
            // this.$router.push({ path: `/system/msg/edit/${rows.id}` })
        })

        // 删除
        this.$bus.$on('handleDelete', rows => {
            this.$confirm('确定删除吗', '取消', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {

                beiGangApi.delAccount(rows.id).then(res => {
                    if (res.code == 200) {
                        this.$message.success("删除成功")
                        this.getAccountList()
                    }
                })
            })
        })
    },
    methods: {
        validateBindStatusDriver(rule, value, callback) {
            let val = this.driverListOptions.filter(item => item.id == value)
            if (val.length) {
                if (Number(val[0].bindStatus) == 1) {
                    return callback(new Error("司机已被其他人绑定"));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        },
        validateBindStatusCom(rule, value, callback) {
            let val = this.companyQueryCompanyList.filter(item => item.id == value)
            if (val.length) {
                if (Number(val[0].bindStatus) == 1) {
                    return callback(new Error("物流公司已被其他人绑定"));
                }
                else {
                    callback();
                }
            } else {
                callback();
            }

        },
        getFormItemDriverRules() {
            const rules = [
                { validator: this.validateBindStatusDriver, required: true, }
            ];
            //   return rules;
            if (this.dictModel.driverId != undefined || this.dictModel.driverId != null || this.dictModel.driverId != '') {
                return rules;
            } else {
                return []

            }
        },
        getFormItemCompanyRules() {
            const rules = [
                { validator: this.validateBindStatusCom, required: true, }
            ];
            //   return rules;
            if (this.dictModel.companyId != undefined || this.dictModel.companyId != null || this.dictModel.companyId != '') {
                return rules;
            } else {
                return []

            }
        },
        // 获取用户详细信息
        getDetail(id) {
            beiGangApi.getAccountDetail(id).then(res => {
                if (res.code == 200) {
                    console.log(res, 'res1');
                    this.dictModel = {
                        id: res.data.id,
                        phone: res.data.phone,
                        isEnabled: res.data.isEnabled == 2 ? true : false,
                        driverId: res.data.driverId,
                        companyId: res.data.companyId,
                    }
                    this.companyQueryCompanyList = [
                        {
                            id: res.data.companyId,
                            companyName: res.data.companyName
                        }
                    ]
                    this.driverListOptions = [
                        {
                            id: res.data.driverId,
                            name: res.data.driverName
                        }
                    ]
                    this.addVisile = true
                    this.isEdit = true

                }
            })
        },
        /*新增编辑下的模糊查询操作start*/
        getDriverQueryBindListWay(query) {
            beiGangApi.getDriverQueryBindList(
                { name: query }
            ).then(res => {
                // if (!response.data.items) return
                if (res.code = 200) {
                    this.driverListOptions = res.data
                }

            })
        },
        getCompanyQueryCompanyListWay(query) {

            beiGangApi.getCompanyQueryCompanyList(
                { companyName: query }
            ).then(res => {
                // if (!response.data.items) return
                this.companyQueryCompanyList = res
                // if(res.code=200){
                //     this.companyQueryCompanyList = res.data
                // }
            })
        },

        /*新增编辑下的模糊查询操作end*/
        // 导出
        exportWay() { 
            this.download('logistics/Account/export', {
                ...this.searchData
            }, `用户管理_${new Date().getTime()}.xlsx`)
            // 
        },
        // 批量操作
        handleCommand(command) {
            //   if (command == "import") {
            //     this.importVisible = true;
            //     console.log("批量导入");
            //   } else if (command == "export") {
            //     this.exportData();
            //     console.log("批量导入");
            //   }
            switch (command) {
                case 'audit':

                    break;
                // 启用
                case 'import':

                    break;
                // 禁用
                case 'export':

                    break;
                // 删除
                default:
                    this.setDel()
                    break;
            }
        },
        // 删除批量操作
        setDel() {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选")
                return
            }
            let content = '确定删除吗'
            let title = '删除'
            if (this.selectArr.length >= 2) {
                title = '批量删除'
                content = `已选择${this.selectArr.length}项，确定要删除吗？`
            }
            this.$confirm(content, title, {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                //   console.log('确认');

                let ids = this.selectArr.map(item => item.id).join(',');
                beiGangApi.delAccount(ids).then(res => {
                    if (res.code == 200) {
                        this.$message.success("操作成功")
                        this.getAccountList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },
        // 创建司机
        add() {
            this.isEdit = false;
            this.addVisile = true;
        },
        handleAddSubmit() {
            this.$refs.dictForm.validate(valid => {
                if (valid) {
                    let obj = {
                        ...this.dictModel,
                        isEnabled: this.dictModel.isEnabled == true ? 2 : 0
                    }
                    if (!this.isEdit) {
                        beiGangApi.addAccount(obj).then(res => {
                            if (res.code == 200) {

                                this.dictModel = this.$options.data().dictModel
                                this.$message.success("添加成功")
                                this.addVisile = false;
                                this.getAccountList()
                                this.driverListOptions = []
                                this.companyQueryCompanyList = []
                                this.resetForm("dictForm")
                            }
                        })
                    } else {
                        beiGangApi.updateAccount(obj).then(res => {
                            if (res.code == 200) {
                                this.dictModel = this.$options.data().dictModel
                                this.$message.success("编辑成功")
                                this.addVisile = false;
                                this.resetForm("dictForm")
                                this.driverListOptions = []
                                this.companyQueryCompanyList = []
                                this.getAccountList()
                            }
                        })
                    }
                } else {
                    this.$message.warning("请检查信息")
                    return false
                }
            })
        },
        handleAddCancle() {

            this.dictModel = this.$options.data().dictModel
            this.resetForm("dictForm")
            this.addVisile = false;
            this.driverListOptions = []
            this.companyQueryCompanyList = []

        },
        // 审核操作
        handleAuditSubmit() {

        },
        handleAuditCancle() {
            this.auditParams = this.$options.data().auditParams
            this.resetForm("auditParams")
            this.auditVisile = false;
        },
        getAccountList() {
            // addDateRange   
            let { pageSize } = this.$refs.tablePage;
            let params = {

                ...this.searchModel,
                pageSize: pageSize,
                pageNum: this.currentPage


            }
            // let obj = addDateRange(params, this.searchModel.loginTime)
            // delete obj.loginTime

            beiGangApi.accountList(params).then(res => {
                if (res.code == 200) {

                    this.total = res.total;
                    this.tableData = res.rows

                }
            })
        },
        selectable(row, index) {
            return true
        },

        handleSearchSubmit() {
            this.currentPage = 1;
            this.getAccountList()
        },
        handleSearchReset() {
            this.currentPage = 1;
            this.$refs.tablePage.clearSelection()
            this.getAccountList()
        },
        handleSizeChange(v) {
            this.pageSize = v;
            this.currentPage = 1;
            this.getAccountList()
        },
        handleCurrentChange(v) {
            this.currentPage = v;
            this.getAccountList()
        },
        handleSelectionChange(v) {
            console.log('handleSelectionChange', v);
            this.selectArr = v
        },
        allot() {
            this.$modal.confirm('是否确认清空所有登录日志数据项？').then(function () {
                return cleanLogininfor();
            }).then(() => {
                this.getAccountList();
                this.$modal.msgSuccess("清空成功");
            }).catch(() => { });
        },




        gethtml(value) {
            if (value == null) {
                return;
            }
            var list = value.split(',');
            var resultStr = ""
            list.forEach(item => {
                if (item.includes("高") || item.includes("重要")) {
                    resultStr = resultStr + "<span style='color:#EE3333'>" + item + "</span>,";
                }
                else {
                    resultStr = resultStr + item + ",";
                }
            })
            if (resultStr != "") {
                return resultStr.slice(0, -1);
            }
        },
        showSettign() {
            getOpenSeaSetting().then(res => {
                if (!res.error) {
                    console.log('getOpenSeaSetting', res);
                    this.ruleModel = res;
                    this.settingVisile = true;
                }
            })
        },
        handleSettingSubmit() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    console.log('ruleModel', this.ruleModel);
                    putOpenSeaStting(this.ruleModel).then(res => {
                        if (!res.error) {
                            this.$message.success("保存设置成功")
                            this.settingVisile = false;
                        }
                    })
                } else {
                    return false
                }
            })
        },
        handleSettingCancle() {
            this.settingVisile = false;
        },
        detailClose() {
            this.detailVisible = false;
            this.getAccountList()
        },
        handleAllot() {
            this.allotVisile = true;
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
    destroyed() {
        this.$bus.$off('handleDetail')
        this.$bus.$off('handleDelete')
        this.$bus.$off('handleEdit')
        this.$bus.$off('handleAudit')


    },
}
</script>
    
<style lang="scss" scoped>
.userSetting_block {

    // padding: 0 .2rem .2rem;
    .top {
        background-color: #fff;
        padding: 0 .3rem;
    }

    .bottom {
        .btn_area {
            margin-bottom: 0.2rem;
            margin-left: 0.3rem;
        }

        background-color: #fff;
        margin-top: 0.2rem;
        padding: 0.2rem 0rem;


    }




    .green {
        color: #2CAD00;
    }

    .orage {
        color: #EE7533;
    }

    .blue {
        color: #0076FF;
    }

    .red {
        color: #ff3333;
    }

    ::v-deep .dirverForm .el-form-item__label:before {
        content: none !important;
    }
}
</style>